package com.cskaoyan.javase.network._1udp._v3;

import com.cskaoyan.javase.network.util.UDPNetworkUtils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Scanner;

/**
 * 第一次接收的接收端(随后可以发送)
 * @since 11:44
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class FirstReceiver {
    public static void main(String[] args) throws IOException {
        // 作为第一次接收端,直接创建接收端的Socket对象
        DatagramSocket socket = new DatagramSocket(7777);
        Scanner sc = new Scanner(System.in);
        while (true) {
            DatagramPacket receiverPacket = UDPNetworkUtils.getReceiverPacket();
            // 获取对方发送来的数据报包,receive,解析
            // 阻塞方法
            socket.receive(receiverPacket);
            System.out.println(UDPNetworkUtils.parsePacket(receiverPacket));

            // 随后进行键盘录入,创建数据报包,send发送消息,这里作为一个发送端
            String msg = sc.nextLine();
            DatagramPacket sendPacket = UDPNetworkUtils.getSendPacket(msg, "127.0.0.1", 6666);
            socket.send(sendPacket);
        }
    }
}
